/******************************************************************************
COPYRIGHT (C) 2013 by IT-Designers GmbH

File:		Measure.cpp
Created:	28.02.2013
Modified:	28.02.2013
Author:		Max Pejs
******************************************************************************/

#include "Measure.h"

Measure* Measure::owner = NULL;

Measure::Measure()
{
	InitializeCriticalSection(&Section);
	UpdateTimer = new Timer("UpdateTimer");
	UpdateTimer->Start();
}

Measure::~Measure()
{
	DeleteCriticalSection(&Section);
}

Measure* Measure::GetInstance()
{
	if(owner == NULL)
	{
		owner = new Measure();
	}
	return owner;
}

Timer * Measure::CreateNewTimer(string id)
{
	EnterCriticalSection(&Section);
	Timer * ret = 0;

	Timer * n = new Timer(id);
	Timer::Comparator cmp(n);

	if(!timerVector.empty())
	{
		std::vector<Timer*>::iterator it = find_if(timerVector.begin(), timerVector.end(), cmp);
		if(it != timerVector.end())
		{
			ret = *it;
			// cout << "ERROR! Timer with name " << id << " already exists";
			// throw;
		}
	}

	if(ret == NULL)
	{
		Timer * newTimer = new Timer(id);
		timerVector.push_back(newTimer);
		ret = newTimer;
	}

	LeaveCriticalSection(&Section);
	return ret;
}

void Measure::PlotMeasure(int updateTimeMs)
{
	EnterCriticalSection(&Section);

	if(UpdateTimer->GetRunTimeInUs()/1000 < updateTimeMs)
	{
		return;
	}

	Mat img = Mat::zeros(500, 500, CV_8UC1);

	for(unsigned int i = 0; i < timerVector.size(); i++)
	{
		ostringstream text;
		Timer * tm = timerVector[i];
		text << tm->Id() << ": " << setiosflags(ios::fixed) << setprecision(3) << tm->GetWeightAvgRunTimeInMs() << " ms";
		putText(img, text.str(), Point(10,20 + i * 20), FONT_HERSHEY_PLAIN, 1.0, CV_RGB(255, 255, 255),1);
	}

	imshow("Time Measures", img);
	
	UpdateTimer->Stop();
	UpdateTimer->Start();

	LeaveCriticalSection(&Section);
}
